package com.migo.utils;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Wes on 2019/1/17.
 */
public class FileMD5Util {

    /**
     * 获取上传文件的md5
     *
     * @param file
     * @return
     * @throws
     * @throws IOException
     */
    public static String getMd5(MultipartFile file) {

        try {
            byte[] uploadBytes = file.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(uploadBytes);
            String hashString = new BigInteger(1, digest).toString(16);
            return hashString;
        } catch (Exception e) {
        }
        return null;

    }


    /**
     * BigInteger 来保存后，再转化成字符串，都会出现首位为0被忽略的现象。
     * 下面的方法可以解决上述的问题
     *
     * @param file
     * @return
     */
    public static String getNewFileMD5(MultipartFile file) {

        StringBuffer stringbuffer = null;
        try {
            char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            CommonsMultipartFile cf = (CommonsMultipartFile) file;
            DiskFileItem fi = (DiskFileItem) cf.getFileItem();
            File f = fi.getStoreLocation();
            FileInputStream in = new FileInputStream(f);
            FileChannel ch = in.getChannel();
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            messagedigest.update(byteBuffer);
            byte[] bytes = messagedigest.digest();
            int n = bytes.length;
            stringbuffer = new StringBuffer(2 * n);
            for (int l = 0; l < n; l++) {
                byte bt = bytes[l];
                char c0 = hexDigits[(bt & 0xf0) >> 4];
                char c1 = hexDigits[bt & 0xf];
                stringbuffer.append(c0);
                stringbuffer.append(c1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringbuffer.toString();

    }

    /**
     * BigInteger 来保存后，再转化成字符串，都会出现首位为0被忽略的现象。
     * 下面的方法可以解决上述的问题
     *
     * @param file
     * @return
     */
    public static String getNewFileMD5(File file) {

        StringBuffer stringbuffer = null;
        try {
            char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            FileInputStream in = new FileInputStream(file);
            FileChannel ch = in.getChannel();
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            messagedigest.update(byteBuffer);
            byte[] bytes = messagedigest.digest();
            int n = bytes.length;
            stringbuffer = new StringBuffer(2 * n);
            for (int l = 0; l < n; l++) {
                byte bt = bytes[l];
                char c0 = hexDigits[(bt & 0xf0) >> 4];
                char c1 = hexDigits[bt & 0xf];
                stringbuffer.append(c0);
                stringbuffer.append(c1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringbuffer.toString();

    }

    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * 获取文件夹中文件的MD5值
     *
     * @param file
     * @param listChild ;true递归子目录中的文件
     * @return
     */
    public static Map<String, String> getDirMD5(File file, boolean listChild) {
        if (!file.isDirectory()) {
            return null;
        }
        //<filepath,md5>
        Map<String, String> map = new HashMap<>();
        String md5;
        File files[] = file.listFiles();
        for (File f : files) {
            if (f.isDirectory() && listChild) {
                map.putAll(getDirMD5(f, listChild));
            } else {
                md5 = getFileMD5(f);
                if (md5 != null) {
                    map.put(f.getPath(), md5);
                }
            }
        }
        return map;
    }


    /**
     *   * get file size 通过URL地址获取文件大小
     *   * @param filePath * url file path
     *   * @return filesize
     *   * @throws MalformedURLException
     *  
     */
    public static String getFileSize(String filePath) throws MalformedURLException {
        HttpURLConnection urlcon = null;
        String size = "";
        URL url = new URL(filePath);
        try {
            //open url
            urlcon = (HttpURLConnection) url.openConnection();
            //get url properties
            size =  String.valueOf(urlcon.getContentLengthLong());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close connect
            urlcon.disconnect();
        }
        return size;
    }


    public static void main(String[] args) {
//        String filePath = "F:/temp/uImage";
//        File file = new File(filePath);
//        Map<String, String> map = getDirMD5(file, true);
//        String key = getNewFileMD5(file);
//        String json = JSON.toJSONString(map);

//        writeToFile(json);
//        System.out.println(key);
        try {
            String size = getFileSize("http://oss.powervision.me/app/20200422/1587547978606/RC.zip");
            System.out.println(size);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


    }


    private static void writeToFile(String str) {
        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(new FileOutputStream("E:/FileMD5.json"), "UTF-8");
            out.write(str);
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
